<?php

namespace app\admin\service;


use app\common\Common;
use app\model\Videos;
use app\model\VideoTypes;
use app\model\VideoDetails;
// use think\facade\Session;
use app\model\WatchPayRecord;
use app\model\PayRecord;
use app\model\Other;
use app\model\Admin;
use think\facade\Cache;
use think\facade\Db;
use app\model\StatisticsVideoRechargeData;
use app\model\ResponsibilityPerson;
use app\model\RechargeLimitTemplate;
use app\model\RechargeLimitTemplateVideo;

class VideoService
{
    private $model;
    private $typeModel;
    private $detailModel;
    private $watchPayRecordModel;
    private $payRecordModel;
    private $otherModel;
    private $adminModel;
    private $statisticsVideoRechargeDataModel;
    private $responsibilityPersonModel;
    private $rechargeLimitTemplate;
    private $rechargeLimitTemplateVideo;

    public function __construct(Videos $model, VideoTypes $typeModel, VideoDetails $detailModel, WatchPayRecord $watchPayRecordModel, PayRecord $payRecordModel, Other $otherModel, Admin $adminModel, StatisticsVideoRechargeData $statisticsVideoRechargeDataModel, ResponsibilityPerson $responsibilityPersonModel,RechargeLimitTemplate $rechargeLimitTemplate , RechargeLimitTemplateVideo $rechargeLimitTemplateVideo)
    {
        $this->model = $model;
        $this->typeModel = $typeModel;
        $this->detailModel = $detailModel;
        $this->watchPayRecordModel = $watchPayRecordModel;
        $this->payRecordModel = $payRecordModel;
        $this->otherModel = $otherModel;
        $this->adminModel = $adminModel;
        $this->statisticsVideoRechargeDataModel = $statisticsVideoRechargeDataModel;
        $this->responsibilityPersonModel = $responsibilityPersonModel;
        $this->rechargeLimitTemplate = $rechargeLimitTemplate;
        $this->rechargeLimitTemplateVideo = $rechargeLimitTemplateVideo;
    }

    // 获取短剧列表
    public function getVideoList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where[] = ['is_delete', '=', 0];
        if (!empty($params['id'])) {
            $where[] = ['id', '=', $params['id']];
        }

        if (!empty($params['name'])) {
            $where[] = ['name', 'like', '%' . $params['name'] . '%'];
        }

        if (!empty($params['video_type_id'])) {
            $where[] = ['video_type_id', '=', $params['video_type_id']];
        }

        $fields = 'id, video_type_id, cover_img, name, label, status, is_shelves, sort, is_free, created_at, is_recommended, type, is_copy, original_id,drama_id';
        $order = 'sort desc, id desc, give_count desc';

        $data = $this->model->getWithRechargeVideoPagingDataByWhere($where, $page, $limit, $fields, $order);

        $typeIds = array_column($data['data'], 'video_type_id');

        $typeData = $this->typeModel->getAllData(['id' => $typeIds]);
        $typeName = array_column($typeData, 'name', 'id');
        $typeTxt = Videos::VIDEO_TYPES;

        foreach ($data['data'] as $key => $item) {
            $data['data'][$key]['video_type_name'] = empty($typeName[$item['video_type_id']]) ? '' : $typeName[$item['video_type_id']];
            $data['data'][$key]['recharge_limit_template_id'] = empty($item['rechargeLimitTemplateVideo']) ? null : $item['rechargeLimitTemplateVideo']['recharge_limit_template_id'];
            $data['data'][$key]['recharge_limit_template_name'] = empty($item['rechargeLimitTemplateVideo']['rechargeLimitTemplate']) ? null : $item['rechargeLimitTemplateVideo']['rechargeLimitTemplate']['recharge_name'];
            $data['data'][$key]['type_txt'] = $typeTxt[$item['type']] ?? '无';
            unset($data['data'][$key]['rechargeLimitTemplateVideo']);
        }

        return $data;
    }

    // 添加/编辑短剧
    public function editVideo($params, $userInfo)
    {
        if (empty($params['id'])) {
            $ossAccessAddress = config('filesystem.alioss.oss_access_address');
            if (strpos($params['cover_img'], $ossAccessAddress['original_access_address']) !== false) {
                $params['cover_img'] = str_replace($ossAccessAddress['original_access_address'], $ossAccessAddress['cdn_accelerated_domain'], $params['cover_img']);
            }
            $params['created_at'] = time();
        } else {
            $params['updated_at'] = time();
        }

        $params['uid'] = $userInfo['user_id'];

        // by huangxiaohsan add 2023-07-24 这个在测试环境和本地环境如果不选中时间，数据库字段会报错，所以加了个默认值进去。
        $params['cooperation_start_time'] = !empty($params['cooperation_start_time']) ? $params['cooperation_start_time'] : '0000-00-00';
        $params['cooperation_end_time'] = !empty($params['cooperation_end_time']) ? $params['cooperation_end_time'] : '0000-00-00';
        // end

        // by huangxiaohsan add 2023-07-24 新增播放短剧在指定平台进行播放。
        $params['play_platform'] = !empty($params['play_platform']) ? implode(',', $params['play_platform']) : '';
        // end
        if (!empty($params['launch_start_time'])) {
            $params['launch_start_time'] = strtotime($params['launch_start_time']);
        }

        Db::startTrans();

        try {
            $id = $this->model->edit($params);

            $insertLimitWhiteData = [];

            if (!empty($params['recharge_limit_template_id'])) {
                $limitData = $this->rechargeLimitTemplate->selectFirstById(['id'], $params['recharge_limit_template_id']);

                if (empty($limitData)) {
                    return false;
                }

                $insertLimitWhiteData[] = [
                    'recharge_limit_template_id' => $params['recharge_limit_template_id'],
                    'video_id' => $id,
                ];
            }

            $this->rechargeLimitTemplateVideo->deleteByVideoId($id);

            if (!empty($insertLimitWhiteData)) {
                $this->rechargeLimitTemplateVideo->insertAll($insertLimitWhiteData);
            }

            $editResponsibilityPersonData = [];

            if (!empty($params['person_ids']) && $personIds = explode(',', $params['person_ids'])) {

                if (empty($params['id'])) {
                    $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere([['id', 'in', $personIds]], ['id', 'video_ids']);

                    if (!empty($responsibilityPersonData)) {
                        foreach ($responsibilityPersonData as $responsibilityPerson) {
                            $editResponsibilityPersonData[] = [
                                'id' => $responsibilityPerson['id'],
                                'video_ids' => !empty($responsibilityPerson['video_ids']) ? implode(',', array_merge(explode(',', $responsibilityPerson['video_ids']), [$id])) : $id
                            ];
                            continue;
                        }
                    }
                } else {
                    $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere([['id', 'in', $personIds]], ['id', 'video_ids']);

                    if (!empty($responsibilityPersonData)) {
                        foreach ($responsibilityPersonData as $responsibilityPerson) {
                            $videoIds = explode(',', $responsibilityPerson['video_ids']);

                            if (in_array($responsibilityPerson['id'], $personIds) && in_array($id, $videoIds)) {
                                continue;
                            }

                            if (in_array($responsibilityPerson['id'], $personIds) && !in_array($id, $videoIds)) {
                                $editResponsibilityPersonData[] = [
                                    'id' => $responsibilityPerson['id'],
                                    'video_ids' => !empty($responsibilityPerson['video_ids']) ? implode(',', array_merge(explode(',', $responsibilityPerson['video_ids']), [$id])) : $id
                                ];
                                continue;
                            }
                        }
                    }

                    $responsibilityPersonData = $this->responsibilityPersonModel->findInSetVideoIds($id, ['id', 'video_ids']);

                    if (!empty($responsibilityPersonData)) {
                        foreach ($responsibilityPersonData as $responsibilityPerson) {
                            $videoIds = explode(',', $responsibilityPerson['video_ids']);
                            if (!in_array($responsibilityPerson['id'], $personIds) && in_array($id, $videoIds)) {
                                $editResponsibilityPersonData[] = [
                                    'id' => $responsibilityPerson['id'],
                                    'video_ids' => implode(',', array_diff($videoIds, [$id]))
                                ];
                                continue;
                            }
                        }
                    }
                }
            }

            if (!empty($params['id']) && empty($params['person_ids'])) {
                $responsibilityPersonData = $this->responsibilityPersonModel->findInSetVideoIds($id, ['id', 'video_ids']);

                if (!empty($responsibilityPersonData)) {
                    foreach ($responsibilityPersonData as $responsibilityPerson) {
                        $videoIds = explode(',', $responsibilityPerson['video_ids']);
                        if (in_array($id, $videoIds)) {
                            $editResponsibilityPersonData[] = [
                                'id' => $responsibilityPerson['id'],
                                'video_ids' => implode(',', array_diff($videoIds, [$id]))
                            ];
                            continue;
                        }
                    }
                }
            }

            $this->responsibilityPersonModel->saveAll($editResponsibilityPersonData);

            Db::commit();

            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
    }

    // 获取短剧详情
    public function getVideoDetail($id)
    {
        $data = $this->model->getWithRechargeVideoInfoById($id, 'id, video_type_id, is_recommended, cover_img, name, label, title_label, status, is_shelves, sort, is_free, is_search, sylloge, partners_id, synopsis, number, scale, type, cooperation_start_time, cooperation_end_time, is_copy, original_id, is_filings, play_platform, launch_start_time,is_money,drama_id');

        $responsibilityPersonData = $this->responsibilityPersonModel->findInSetVideoIds($id, ['id']);

        $data['responsibility_ids'] = [];

        if (!empty($responsibilityPersonData)) {
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');

            $data['responsibility_ids'] = $responsibilityPersonIds;
        }
        $data['launch_start_time'] = date('Y-m-d H:i:s', $data['launch_start_time']);
        $data['recharge_limit_template_id'] = empty($data['rechargeLimitTemplateVideo']) ? null : $data['rechargeLimitTemplateVideo']['recharge_limit_template_id'];
        unset($data['rechargeLimitTemplateVideo']);
        return $data;
    }

    // 获取剧集列表
    public function getVideoDetailList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $data = $this->detailModel->getPagingDataByWhere(['video_id' => $params['video_id']], $page, $limit, 'id, sort, is_pay, is_members, pay_amount, created_at, third_url as url');

        return $data;
    }

    // 删除短剧
    public function deleteVideo($id)
    {
        Db::startTrans();

        try {
            $this->model->edit(['id' => $id, 'is_delete' => 1, 'updated_at' => time()]);

            $this->detailModel->where(['video_id' => $id])->update(['is_delete' => 1, 'updated_at' => time()]);

            $responsibilityPersonData = $this->responsibilityPersonModel->findInSetVideoIds($id, ['id', 'video_ids']);

            if (!empty($responsibilityPersonData)) {
                $editResponsibilityPersonData = [];
                foreach ($responsibilityPersonData as $responsibilityPerson) {
                    $videoIds = explode(',', $responsibilityPerson['video_ids']);
                    if (in_array($id, $videoIds)) {
                        $editResponsibilityPersonData[] = [
                            'id' => $responsibilityPerson['id'],
                            'video_ids' => implode(',', array_diff($videoIds, [$id]))
                        ];
                        continue;
                    }
                }

                $this->responsibilityPersonModel->saveAll($editResponsibilityPersonData);
            }

            $this->rechargeLimitTemplateVideo->deleteByVideoId($id);

            Db::commit();

            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
    }

    // 短剧上下架
    public function videoUpperAndLowerShelves($id)
    {
        $data = $this->model->getInfoById($id, 'is_shelves');

        if (empty($data)) {
            return false;
        }

        $saveData = ['id' => $id, 'updated_at' => time()];

        if ($data['is_shelves'] == 1) {
            $saveData['is_shelves'] = 0;
        } else {
            $saveData['is_shelves'] = 1;
        }

        $bool = $this->model->edit($saveData);

        if (!$bool) {
            return false;
        }

        return true;
    }

    // 短剧统计列表
    public function getVideoStatisticsList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where[] = ['is_delete', '=', 0];
        if (!empty($params['id'])) {
            $where[] = ['id', '=', $params['id']];
        }

        if (!empty($params['name'])) {
            $where[] = ['name', 'like', '%' . $params['name'] . '%'];
        }

        if (!empty($params['video_type_id'])) {
            $where[] = ['video_type_id', '=', $params['video_type_id']];
        }

        $fields = 'id, video_type_id, name, frequency, number, total_consume';
        $order = 'sort desc, id desc, give_count desc';

        $data = $this->model->getPagingDataByWhere($where, $page, $limit, $fields, $order);
        // 所属分类
        $typeIds = array_column($data['data'], 'video_type_id');
        $typeData = $this->typeModel->getAllData(['id' => $typeIds]);
        $typeName = array_column($typeData, 'name', 'id');

        $videoIds = array_column($data['data'], 'id');
        $toDay = date('Ymd');
        $yesterDay = date('Ymd', time() - 24 * 60 * 60);

        $redis = Cache::store('redis')->handler();
        $redis->select(2);
        $totalRecharge=json_decode($redis->get('totalRecharge_log_three'),true);
        if(empty($totalRecharge)){
            // 今日消耗
            $toDayConsume = $this->watchPayRecordModel->getInfo(['video_id' => $videoIds, 'consume_date' => $toDay], 'video_id, money');
            $toDayConsumeData = [];
            foreach ($toDayConsume as $key => $value) {
                $toDayConsumeData[$value['video_id']] =empty($toDayConsumeData[$value['video_id']])? $value['money']:(int)$toDayConsumeData[$value['video_id']]+ (int)$value['money'];
            }

            // 昨日消耗
            $yesterDayConsume = $this->watchPayRecordModel->getInfo(['video_id' => $videoIds, 'consume_date' => $yesterDay], 'video_id, money');
            $yesterDayConsumeData = [];
            foreach ($yesterDayConsume as $key => $value) {
                $yesterDayConsumeData[$value['video_id']] =empty($yesterDayConsumeData[$value['video_id']])? $value['money']:(int)$yesterDayConsumeData[$value['video_id']]+ (int)$value['money'];
            }
   
        // 今日充值
        $toDayRechargeData = [];

        // 昨日充值
        $yesterDayRechargeData = [];

        // 总充值

            $totalRecharge = $this->payRecordModel->getInfo(['consume_date' => [$toDay,$yesterDay], 'status' => 1], 'video_id, total_fee, consume_date');
       
            $totalRechargeData = [];
            foreach ($totalRecharge as $key => $value) {
                $totalRechargeData[$value['video_id']]=empty($totalRechargeData[$value['video_id']])? $value['total_fee']:$totalRechargeData[$value['video_id']]+ $value['total_fee'];
                if ($value['consume_date'] == $toDay) {
                    $toDayRechargeData[$value['video_id']]= empty($toDayRechargeData[$value['video_id']])? $value['total_fee']:$toDayRechargeData[$value['video_id']]+ $value['total_fee'];
                }
                if ($value['consume_date'] == $yesterDay) {
                    $yesterDayRechargeData[$value['video_id']]= empty($yesterDayRechargeData[$value['video_id']])? $value['total_fee']:$yesterDayRechargeData[$value['video_id']]+ $value['total_fee'];
                }
            }
            $redis->set('totalRecharge_log_three',json_encode(['yesterDayConsumeData'=>$yesterDayConsumeData,'toDayConsumeData'=>$toDayConsumeData,'totalRechargeData'=>$totalRechargeData,'toDayRechargeData'=>$toDayRechargeData,'yesterDayRechargeData'=>$yesterDayRechargeData]),10*60);
        }else{
            $yesterDayConsumeData=$totalRecharge['yesterDayConsumeData'];
            $toDayConsumeData=$totalRecharge['toDayConsumeData'];
            $totalRechargeData=$totalRecharge['totalRechargeData'];
            $toDayRechargeData=$totalRecharge['toDayRechargeData'];
            $yesterDayRechargeData=$totalRecharge['yesterDayRechargeData'];
        }

       
        $videoKey = config('redis_key.video_statistic_count_key');
        $videoInfo = $redis->hGetAll($videoKey) ?: [];

        foreach ($data['data'] as $key => $item) {
            $data['data'][$key]['video_type_name'] = empty($typeName[$item['video_type_id']]) ? '' : $typeName[$item['video_type_id']];

            $data['data'][$key]['today_consume'] = empty($toDayConsumeData[$item['id']]) ? 0 : $toDayConsumeData[$item['id']];
            $data['data'][$key]['yesterday_consume'] = empty($yesterDayConsumeData[$item['id']]) ? 0 : $yesterDayConsumeData[$item['id']];
            // $data['data'][$key]['total_consume'] = empty($totalConsumeData[$item['id']]) ? 0 : array_sum($totalConsumeData[$item['id']]);

            $data['data'][$key]['today_recharge'] = empty($toDayRechargeData[$item['id']]) ? 0 : round($toDayRechargeData[$item['id']], 2);
            $data['data'][$key]['yesterday_recharge'] = empty($yesterDayRechargeData[$item['id']]) ? 0 : round($yesterDayRechargeData[$item['id']], 2);
            $data['data'][$key]['total_recharge'] = empty($totalRechargeData[$item['id']]) ? 0 : round($totalRechargeData[$item['id']], 2);

            $total_consume_cache = $videoInfo['total_consume_'.$item['id']] ?? 0;
            $data['data'][$key]['total_consume'] = $item['total_consume'] + $total_consume_cache;

            $frequency_cache = $videoInfo['frequency_'.$item['id']] ?? 0;
            $data['data'][$key]['frequency'] = $item['frequency'] + $frequency_cache;

            $number_cache = $videoInfo['number_'.$item['id']] ?? 0;
            $data['data'][$key]['number'] = $item['number'] + $number_cache;
        }

        return $data;
    }

    // 短剧统计详情
    public function getVideoStatisticsDetail($params)
    {
        $videoId = $params['id'];
        $videoName = $params['name'];
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 15;

        $data = $this->detailModel->getPagingDataByWhere(['video_id' => $videoId], $page, $limit, 'id, name, is_pay, pay_amount, number');

        if ($data['data']) {
            $redis = Cache::store('redis')->handler();
            $redis->select(2);
            $videoDetailKey = config('redis_key.video_detail_statistic_count_key').$videoId;
            $detailInfo = $redis->hGetAll($videoDetailKey) ?: [];

            $ids = array_column($data['data'], 'id');

            $consumeDate = $this->watchPayRecordModel->getInfo(['video_id' => $videoId, 'video_detail_id' => $ids], 'video_detail_id, money, consume_date');
            $consume = [];
            foreach ($consumeDate as $key => $value) {
                $consume[$value['video_detail_id']][] = $value;
            }

            $toDay = date('Ymd');
            foreach ($data['data'] as $key => $value) {
                $totalConsume = $toDayConsume = 0;
                $watchUserNum = $toDayWatchUserNum = 0;
                if (!empty($consume[$value['id']])) {
                    foreach ($consume[$value['id']] as $k => $item) {
                        $totalConsume += $item['money'];
                        $watchUserNum += 1;
                        if ($item['consume_date'] == $toDay) {
                            $toDayConsume += $item['money'];
                            $toDayWatchUserNum += 1;
                        }
                    }
                }
                $number = $value['number'] + ($detailInfo['number_'.$value['id']] ?? 0);
                $data['data'][$key]['video_name'] = $videoName;
                $data['data'][$key]['total_consume'] = $totalConsume;
                $data['data'][$key]['today_consume'] = $toDayConsume;
                $data['data'][$key]['watch_user_num'] = empty($watchUserNum) ? (int)$number : $watchUserNum;
                $data['data'][$key]['today_watch_user_num'] = $toDayWatchUserNum;
            }
        }
        return $data;
    }

    // 剧集详情
    public function getDetailsOfEachEpisode(int $id)
    {
        $data = $this->detailModel->getInfoById($id, 'id, name, video_id, is_pay, pay_amount, is_members, third_url as url, sort, give_count, share_count');

        return $data;
    }

    // 添加/编辑剧集
    public function editVideoDetail($params)
    {
        $videoData = $this->model->getInfoById($params['video_id'], 'sylloge');
        if (empty($params['id'])) {
            $params['created_at'] = time();

            // 判断当前剧集是否等于总集数，等于短剧状态置为已完结
            $saveData = [
                'id' => $params['video_id'],
                'update_sort' => $params['sort'],
                'updated_at' => time()
            ];
            if (intval($params['sort']) == intval($videoData['sylloge'])) {
                // 修改状态为已完结
                $saveData['status'] = 1;
            }

            // 判断最近的一集是否收费
            if ($params['sort'] > 1) {
                $lastDetailData = $this->detailModel->getInfoByWhere(['video_id' => $params['video_id']], 'is_pay, pay_amount, is_members', 'sort desc');

                if ($lastDetailData) {
                    $params['is_pay'] = $lastDetailData['is_pay'];
                    $params['pay_amount'] = $lastDetailData['pay_amount'];
                    $params['is_members'] = $lastDetailData['is_members'];
                }
            }

            $this->model->edit($saveData);
        } else {
            $params['updated_at'] = time();
            $detail = $this->detailModel->getInfoById($params['id'],'id,platform_config');
            $platformConf = $detail ? $detail['platform_config'] : [];
        }

        $ossAccessAddress = config('filesystem.alioss.oss_access_address');
        if (strpos($params['url'], $ossAccessAddress['original_access_address']) !== false) {
            $params['third_url'] = str_replace($ossAccessAddress['original_access_address'], $ossAccessAddress['cdn_accelerated_domain'], $params['url']);
            //编辑视频需要重新上传抖音云
            if (isset($platformConf) && !empty($platformConf)) {
                $dyConf = $platformConf['douyinyun'] ?? [];
                if ($dyConf && $dyConf['upload_status']) {
                    $dyConf['upload_status'] = 0;
                    $dyConf['binding_status'] = 0;
                    $dyConf['open_video_id'] = '';

                    $platformConf['douyinyun'] = $dyConf;
                    $params['platform_config'] = $platformConf;
                }
            }
        }

        $id = $this->detailModel->edit($params);

        if (!is_numeric($id)) {
            return false;
        }

        return true;
    }

    // 删除视频
    public function deleteVideoDetail($id)
    {
        // 获取短剧id
        $data = $this->detailModel->getInfoById($id, 'video_id');
        // 删除指定剧集
        $bool = $this->detailModel->destroy($id);

        $videoId = $data['video_id'];
        // 删除后获取该短剧最高的剧集
        $sortData = $this->detailModel->getDataByWhere(['video_id' => $videoId], 'sort', 'sort desc', 1);
        if (!empty($sortData[0])) {
            $videoData = $this->model->getInfoById($videoId, 'sylloge, status');
            // 删除后修改更新到多少集
            $saveData = [
                'id' => $videoId,
                'update_sort' => $sortData[0]['sort'],
                'updated_at' => time()
            ];
            if ($videoData['sylloge'] > $sortData[0]['sort']) {
                // 总集数大于该剧最高集数
                $saveData['status'] = 0;
            }
            $this->model->edit($saveData);
        }

        if (!$bool) {
            return false;
        }

        return true;
    }

    // 添加/编辑指定发布者的其他短剧
    public function editPublisherOtherVideo($params)
    {
        if (empty($params['id'])) {
            $params['created_at'] = time();
        } else {
            $params['updated_at'] = time();
        }

        $id = $this->otherModel->edit($params);

        if (!$id) {
            return false;
        }

        return true;
    }

    // 获取其他视频发布者列表
    public function getPublisherOtherVideoList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where = [];
        $data = $this->otherModel->getPagingDataByWhere($where, $page, $limit, 'id, admin_uid, video_id');

        if (!empty($data['data'])) {

            $adminUids = $videoIds = $videoIdsArray = [];

            foreach ($data['data'] as $key => $item) {
                $adminUids[] = $item['admin_uid'];
                $videoIds = explode(',', $item['video_id']);
                foreach ($videoIds as $value) {
                    $videoIdsArray[] = $value;
                    $videoId[] = ['id' => $value];
                }
                $data['data'][$key]['video_id'] = $videoId;
            }

            $videoIdsArray = array_unique($videoIdsArray);

            $adminUserData = $this->adminModel->getDataByWhere(['id' => $adminUids], 'id, name');
            $adminUser = array_column($adminUserData, 'name', 'id');

            $videoData = $this->model->getDataByIds($videoIdsArray, 'id, name');
            $video = array_column($videoData, 'name', 'id');

            foreach ($data['data'] as $key => $item) {
                $item['admin_user_name'] = empty($adminUser[$item['admin_uid']]) ? '' : $adminUser[$item['admin_uid']];

                foreach ($item['video_id'] as $k => $value) {
                    // dump($value);die;
                    $item['video_id'][$k]['name'] = empty($video[$value['id']]) ? '' : $video[$value['id']];
                }
                $data['data'][$key] = $item;
            }
        }
        return $data;
    }

    // 指定发布者的短剧详情
    public function getPublisherOtherVideoDetail($id)
    {
        $data = $this->otherModel->getInfoById($id, 'id, admin_uid, video_id');
        $data['video_id'] = explode(',', $data['video_id']);

        return $data;
    }

    // 删除发布者的其他推荐短剧
    public function deletePublisherOtherVideo(int $id)
    {
        $bool = $this->otherModel->destroy($id);

        if (!$bool) {
            return false;
        }

        return true;
    }

    // 获取短剧下拉列表
    public function getVideoSelectList($params, ?int $is_shelves = 1)
    {
        $where = [
            ['is_delete', '=', 0]
        ];
        if (!is_null($is_shelves)) {
            $where[] = ['is_shelves', '=', $is_shelves];
        }
        if (!empty($params['name'])) {
            $where[] = ['name', 'like', '%' . $params['name'] . '%'];
        }
        $data = $this->model->getDataByWhere($where, 'id, name');
        if(!empty($data)) {
            foreach($data as $key => $value) {
                $data[$key]['name'] = $value['id'].'-'.$value['name'];
            }
        }
        return $data;
    }

    // 获取指定发布者的短剧下拉列表
    public function getPublisherVideoSelectList($uid)
    {
        // $uid = Session::get('user_id');
        $data = $this->model->getDataByWhere(['uid' => $uid, 'is_delete' => 0, 'is_shelves' => 1], 'id, name');

        return $data;
    }

    // 设为/取消推荐
    public function setAsRecommended(int $id)
    {
        $data = $this->model->getInfoById($id, 'is_recommended');

        if ($data['is_recommended'] == 0) {
            // 设为推荐
            $boolId = $this->model->edit(['id' => $id, 'is_recommended' => 1, 'updated_at' => time()]);
        } else {
            // 取消推荐
            $boolId = $this->model->edit(['id' => $id, 'is_recommended' => 0, 'updated_at' => time()]);
        }

        if (!$boolId) {
            return false;
        }

        return true;
    }

    // 设置从第多少集后开始收费
    public function setCharge($params)
    {
        $where = [
            ['video_id', '=', $params['video_id']],
            ['sort', '>=', $params['sort']]
        ];

        $bool = $this->detailModel->where($where)->update([
            'is_pay' => 1,
            'pay_amount' => $params['pay_amount']
        ]);

        if (!$bool) {
            return false;
        }

        return true;
    }

    // 取消收费
    public function cancelCharge($params)
    {
        $sort = $params['sort'];
        $videoId = $params['video_id'];

        $where = [
            ['video_id', '=', $videoId],
            ['sort', '<=', $sort]
        ];

        $bool = $this->detailModel->where($where)->update([
            'is_pay' => 0,
            'pay_amount' => 0
        ]);

        if (!$bool) {
            return false;
        }

        return true;
    }

    // 批量添加剧集
    public function batchAddVideoDetail($params)
    {
        // 
        try {
            //code...
   
        $saveData = $params['data'];

        $videoId = $saveData[0]['video_id'];
        $data = $this->detailModel->getDataByWhere(['video_id' => $videoId], 'id, sort');
        $videoData = $this->model->getInfoById($videoId, 'sylloge, update_sort');
        $updateSort = $videoData['update_sort'];

        if ($data) {
            $detailData = array_column($data, 'id', 'sort');

            foreach ($saveData as $key => $item) {
                if (!empty($detailData[$item['sort']])) {
                    // 修改
                    $saveData[$key]['id'] = $detailData[$item['sort']];
                } else {
                    $updateSort = $updateSort + 1;
                }
            }
        } else {
            $updateSort = count($saveData);
        }

        $ossAccessAddress = config('filesystem.alioss.oss_access_address');
        foreach ($saveData as $key => $item) {
            // 替换成cdn域名
            if (strpos($item['url'], $ossAccessAddress['original_access_address']) !== false) {
                $saveData[$key]['url'] = str_replace($ossAccessAddress['original_access_address'], $ossAccessAddress['cdn_accelerated_domain'], $item['url']);
            }
            if(!empty($saveData[$key]['url'])){
                $saveData[$key]['third_url']=$saveData[$key]['url'];
            }
            $saveData[$key]['give_count'] = rand(2500, 5000);
            $saveData[$key]['share_count'] = rand(2000, 4000);
        }

        $id = $this->detailModel->saveAll($saveData);

        // 修改videos表数据是否完结、更新集数
        $videoSaveData = [
            'id' => $videoId,
            'update_sort' => $updateSort,
            'status' => 0,
            'updated_at' => time()
        ];
        if ($updateSort == $videoData['sylloge']) {
            $videoSaveData['status'] = 1;
        }

        $this->model->edit($videoSaveData);

        return $id ? true : ['msg'=>'上传失败'];
        } catch (\Throwable $th) {
            //throw $th;
            return ['msg'=>'剧名不规范，请规范剧名为，数字1、2、...'];
        }
    }
    //切流id
    public function getFlow($videoId){
        $videoData = $this->model->getInfoById($videoId, 'drama_id');
        if(!empty($videoData)){
            $host_url=config('app.app_host');
            $url="https://{$host_url}/admin/task/updateWechatVideoPlayUrl?drama_id=". $videoData['drama_id'];
            $list=Common::curlGetRequestHeader($url, ['Content-Type:application/json']);
            $this->clearVideoCache();
            $redis = Cache::store('redis')->handler();
            $redis->select(5);
            $redis->del('openweixin_drama_data:'.$videoData['drama_id']);
        }
        return true;
        
    }
    // 批量删除剧集
    public function batchDeleteVideoDetail($params)
    {
        $idArray = explode(',', $params['id_string']);

        $bool = $this->detailModel->where(['id' => $idArray])->delete();

        return $bool ? true : false;
    }

    // 清理短剧缓存
    public function clearVideoCache()
    {
        $redis = Cache::store('redis')->handler();

        $redis->select(7);

        //$key1 = config('redis_key.api_home_video_recommend_list') . '1';
        $key2 = config('redis_key.get_video_data_by_video_id');

        //首页数据缓存的清理
        $key3 = '*' . config('redis_key.api_home_video_recommend_list') . '*';
        $key3List = $redis->keys($key3);
        foreach ($key3List as $k3 => $v3) {
            $redis->del($key3List[$k3]);
        }

        //$redis->del($key1);
        $videoData = $this->model->getDataByWhere(['is_delete' => 0, 'is_shelves' => 1], 'id');
        foreach ($videoData as $item) {
            $redis->del($key2 . $item['id']);
        }

        //清除热门、最新、免费缓存
        $type_api_video_key = 'api-video-*-list-*';
        $type_tiktok_api_video_key = 'tiktok-api-video-*-list-*';
        $type_api_video_key_list = $redis->keys($type_api_video_key);
        foreach ($type_api_video_key_list as $apiKey) {
            $redis->del($apiKey);
        }

        $tiktok_api_video_key_list = $redis->keys($type_tiktok_api_video_key);
        foreach ($tiktok_api_video_key_list as $tiktokApiKey) {
            $redis->del($tiktokApiKey);
        }

        $banner_api_video_key = 'banner-video*';
        $banner_api_video_key_list = $redis->keys($banner_api_video_key);
        foreach ($banner_api_video_key_list as $bannerApiKey) {
            $redis->del($bannerApiKey);
        }

        return true;
    }

    // 获取短剧的人均充值
    public function getPerCapitaByVideo(array $params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where = [];
        // 短剧id搜索
        if (!empty($params['video_id'])) {
            $where['video_id'] = $params['video_id'];
        }

        // 模板id搜索
        if (!empty($params['recharge_template_id'])) {
            $where['recharge_template_id'] = $params['recharge_template_id'];
        }

        $data = $this->statisticsVideoRechargeDataModel->getPagingDataByWhere($where, $page, $limit, 'sum(recharge_price) as recharge_price, video_id, video_name, recharge_template_id, recharge_template_name, recharge_template_type, sum(recharge_people_num) as recharge_people_num');

        foreach ($data['data'] as $key => $item) {
            // 计算人均
            $data['data'][$key]['per_capita'] = round($item['recharge_price'] / $item['recharge_people_num'], 2);
        }
        return $data;
    }
}
